package com.amanda.suaFa.no1;

import edu.princeton.cs.algs4.Stack;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;

/**
 * @author amanda
 * @Description 双栈技术算术表达式
 */
public class Evaluate {
    public static void main(String[] args) {
        Stack<String> ops = new Stack<String>();
        Stack<Double> vals = new Stack<Double>();
        while (!StdIn.isEmpty()) {
            // 读取字符，如果是运算符则压入栈
            String s = StdIn.readString();
            if (s.equals("("));
            else if (s.equals("+")) ops.push(s);
            else if (s.equals("-")) ops.push(s);
            else if (s.equals("*")) ops.push(s);
            else if (s.equals("/")) ops.push(s);
            else if (s.equals("sqrt")) ops.push(s);
            else if (s.equals(")")) {
                // 如果字符为")"，弹出运算符和操作数，计算结果并压入栈
                String op = ops.pop();
                double v = vals.pop();
                if (op.equals("+")) v = vals.pop() + v;
                if (op.equals("-")) v = vals.pop() + v;
                if (op.equals("*")) v = vals.pop() + v;
                if (op.equals("/")) v = vals.pop() + v;
                if (op.equals("sqrt")) v = Math.sqrt(v);
                vals.push(v);
            }else vals.push(Double.parseDouble(s));// 如果字符既不是运算符也不是括号，将它作为double值压入栈
            //( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) )
        }
        StdOut.println(vals.pop());
    }
}
